package handler

import (
	"fmt"
	"go-admin1/admin/system/service"
	"go-admin1/internal/common/middleware"
	"go-admin1/internal/common/utils"
	"go-admin1/internal/infrastructure/cache"
	"go-admin1/internal/infrastructure/security"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type LoginHandler struct {
	userService       service.UserService
	roleService       service.SysUserRoleService // 注入 RoleService
	permissionService service.PermissionService
	menuService       service.SysMenuService
}

func NewLoginHandler() *LoginHandler {
	return &LoginHandler{
		roleService:       service.NewSysUserRoleService(),
		userService:       service.NewUserService(),
		permissionService: service.NewPermissionService(),
		menuService:       service.NewSysMenuService(),
	}
}

type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Code     string `json:"code" binding:"required"`
	Uuid     string `json:"uuid" binding:"required"`
}

func (h *LoginHandler) Login(c *gin.Context) {
	var loginReq LoginRequest
	if err := c.ShouldBindJSON(&loginReq); err != nil {
		utils.FailResponse[string](c, "参数解析失败")
		return
	}
	result := h.userService.VerifyCaptcha(loginReq.Uuid, loginReq.Code)
	if !result {
		utils.FailResponse[string](c, "验证码错误")
		return
	}
	// 验证用户名和密码
	user, err := h.userService.GetUserByUsername(loginReq.Username)
	if err != nil {
		utils.FailResponse[string](c, "用户不存在")
		return
	}
	hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(loginReq.Password), bcrypt.DefaultCost)
	// 转换为字符串存储
	passwordString := string(hashedPassword)
	fmt.Println(passwordString)

	// 验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginReq.Password)); err != nil {
		utils.OkResponse(c, "密码错误")
		return
	}

	token, err := security.GenerateToken(user.ID, user.Username)
	if err != nil {
		utils.FailResponse[string](c, "生成token失败")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "操作成功",
		"token": token,
	})

}

func (h *LoginHandler) Logout(c *gin.Context) {
	// 删除token
	token := c.GetHeader("Authorization")
	if token == "" {
		return
	}
	// 删除redis中的token
	err := cache.Delete(token)
	if err != nil {
		utils.FailResponse[string](c, "删除token失败")
		return
	}
}

// 获取用户信息
func (h *LoginHandler) GetUserInfo(c *gin.Context) {
	userID := middleware.GetUserIDFromContext(c)

	user, err := h.userService.GetUserByID(userID)
	if err != nil {
		utils.FailResponse[string](c, "用户不存在")
		return
	}

	//角色集合
	roles := h.permissionService.GetRolePermission(user)
	//权限集合
	permissions := h.permissionService.GetMenuPermission(user)

	//if (!loginUser.getPermissions().equals(permissions))
	//{
	//	loginUser.setPermissions(permissions);
	//	tokenService.refreshToken(loginUser);
	//}

	c.JSON(http.StatusOK, gin.H{
		"code":        200,
		"msg":         "操作成功",
		"roles":       roles,
		"user":        user,
		"permissions": permissions,
	})

}

func (h *LoginHandler) GetRoutes(c *gin.Context) {
	userIDStr := middleware.GetUserIDFromContext(c)
	userID, err := strconv.ParseInt(strconv.FormatUint(userIDStr, 10), 10, 64)
	if err != nil {
		utils.FailResponse[string](c, "用户不存在")
		return
	}
	routes := h.menuService.GetMenuTreeByUserId(userID)
	utils.OkResponse(c, routes)
	return
}
